package com.example.jh352160.surfingtv.search.customView;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.example.jh352160.surfingtv.R;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by jh352160 on 2016/8/1
 */

public class HistoryList extends LinearLayout {

    Context context;
    LinearLayout cleanAll;
    ListView historyList;
    List<String> stringList;

    public HistoryList(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public HistoryList(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    private void init() {
        LayoutInflater.from(context).inflate(R.layout.search_history_list, this);
        cleanAll = (LinearLayout) findViewById(R.id.clean_all);
        historyList = (ListView) findViewById(R.id.history_list);
        flushList();
    }

    public void cleanAllHistory() {
        SharedPreferences.Editor editor = context.getSharedPreferences("search_history", MODE_PRIVATE).edit();
        editor.clear();
        editor.apply();
        stringList = new ArrayList<>();
        ListAdapter adapter = new ArrayAdapter<>(context, R.layout.search_history_list_item, R.id.text, stringList);
        historyList.setAdapter(adapter);
    }

    public void flushList() {
        boolean haveData = false;
        stringList = new ArrayList<>();
        SharedPreferences preferences = context.getSharedPreferences("search_history", Context.MODE_PRIVATE);
        for (int i = 0; i < 10; i++) {
            if (preferences.contains("string" + i)) {
                stringList.add(preferences.getString("string" + i, ""));
            } else {
                break;
            }
        }
        if (stringList.size() != 0) {
            haveData = true;
        }
        ListAdapter adapter = new ArrayAdapter<>(context, R.layout.search_history_list_item, R.id.text, stringList);
        historyList.setAdapter(adapter);
        if (!haveData) {
            this.setVisibility(View.INVISIBLE);
        } else {
            this.setVisibility(VISIBLE);
        }
    }
}
